
from flask import Blueprint,render_template,request,redirect,session
from .model import db
from .utils import tools
import json,base64,uuid,os



us = Blueprint('user',__name__,template_folder="templates", static_folder="static", static_url_path="/static")

# template_folder：指定HTML文件查找目录
# static_folder：指定静态资源存放目录
# static_url_path：HTML中静态资源的标志 

@us.before_request
def check_login():
	print(request.user_agent)
	user_info = get_user()
	if not user_info and request.path in [
			'/user',
			'/contribu',
			'/user_contr'
			
		]:
		return redirect('/login')

	return None


#获取用户信息
def get_user():
	username = session.get('user_info')
	user_info = db.fetch_all('''select * from xxxxxx where xxxxxx='{}' '''.format(username,))
	if user_info:
		user_info = user_info[0]
	return user_info




#视图
@us.route('/search')
def search():
	res = db.fetch_all('select * from xxxxxx t')
	menu = db.fetch_all('select distinct gjzwmc from xxxxxx t')
	time_data={}
	time_data['res']=res
	time_data['menu']=menu
	return render_template('search.html',mes=time_data)
	

@us.route('/login',methods=['GET','POST'])
def login():
	if request.method == 'GET':
			ios = request.user_agent.string.split(' ')
			if 'Android' in ios or 'iPhone' in ios :
				return render_template('index_mobile.html')
			return render_template('index.html')

	username = request.form.get('username')
	password = request.form.get('password')
	first_login = request.form.get('check')
	
	pwd = tools.password_md5(password)

	sql =''' select pwd from xxxxxx where xxxxxx='{}' '''.format(username.replace(' ',''))
	res = db.fetch_all(sql)

	#首次登陆即注册
	if first_login and not res:
		sql = '''insert into t_users values(0,'{0}','','','{1}',sysdate(),'Y')'''.format(username,pwd)
		db.insert_one(sql)
		session['user_info'] = username
		return redirect('/')
	else:
		if res and res[0].get('pwd') == pwd:
			session['user_info'] = username
			return redirect('/')
		else:
			return redirect('/login?tips=username_or_password_not_exists_or_wrong!')



@us.route('/')
def main():
	user_info = get_user()
	fl_list = ['10','20','30']
	ctx={}
	sql = 'select x.uuid,x.need_name,x.intro from xxxxxx x where fl="{}" order by rand() limit 9'
	for fl in fl_list:
		ctx['img'+fl] = db.fetch_all(sql.format(fl,))
	ctx['user_info'] = user_info
	#默认为登陆状态
	role = 2
	if not user_info:
		ctx['user_info'] = {'username':'游客'}
		#如果没有登陆则标记为游客
		role = 1
	#根据身份或取菜单
	menu_list = db.fetch_all('select gn_dm,gnmc from xxxxxx where yxbz="Y" and role="{}"'.format(role,))
	ctx['menu_list'] = menu_list
	return render_template('main.html',ctx = ctx)


@us.route('/contribu')
def contribu():
	return render_template('contribu.html')

@us.route('/about')
def about():
	return render_template('about.html')


@us.route('/user')
def user():
	user_info = get_user()
	res = db.fetch_all('select count(1) sl from xxxxxx where user_id="{}"'.format(user_info.get('id')))
	user_info['gx']=res[0].get('sl')
	return render_template('user.html',user_info = user_info)


@us.route('/logout')
def logout():
	session.clear()
	return redirect('/login')


#数据处理
@us.route('/query',methods=['GET','POST'])
def query():
	if request.method == 'GET':
		return redirect('/index')

	query_info = request.form

	#获取前台查询条件
	dz = query_info.get('qy_dz')
	country = query_info.get('qy_gj')
	fl = query_info.get('qy_fl')
	rqq = int(query_info.get('qy_rqq'))
	rqz = int(query_info.get('qy_rqz'))
	info = query_info.get('qy_info')
	cxfs = query_info.get('qy_cxfs')
	#精确查询和相关查询
	sql_filter2 = 'and x.intro like "%{0}%"' if cxfs == '1' else 'and x.need_name like "%{0}%"'
	sql_filter2 = sql_filter2.format(info,)
	sql_filter = ''
	 
	sql = ''
	sql_base = '''
				select x.uuid, x.need_name, x.rqq, x.rqz, intro intro,x.country
				  from xxxxxx x,xxxxxx j
				 where x.country = j.gjzwmc
				   {0}
				   {1}
				   and x.fl ='{2}'
				   and x.rqz >= {3}
				   and x.rqq <= {4}
				   and x.yxbz='Y'
		'''

	if dz == 'ALL':
		sql  = sql_base.format(sql_filter2,sql_filter,fl,rqq,rqz)
	elif dz != 'ALL' and country == 'ALL':
		sql_filter = 'and j.dz ="'+ dz +'"'
		sql  = sql_base.format(sql_filter2,sql_filter,fl,rqq,rqz)
	else:
		sql_filter = 'and j.gj3_dm = "'+ country+'"'
		sql  = sql_base.format(sql_filter2,sql_filter,fl,rqq,rqz)

	res = db.fetch_all(sql)
	#增加查询总数信息
	count = len(res)
	#限制展示数量
	res = res[:50]
	ctx={}
	ctx['res']=res
	ctx['count']=count
	return json.dumps(ctx)


#根据大洲显示国家信息
@us.route('/get_gj',methods=['GET','POST'])
def get_gj():
	if request.method == 'GET':
		return redirect('/index')
	dz = request.form.get('dz')
	list_gj = db.fetch_all('''select gjzwmc,gj3_dm from xxxxxx where yxbz='Y' and dz=\'{}\''''.format(dz,))
	return json.dumps(list_gj)

	 
#返回对象详细信息
@us.route('/get_xxxx',methods =['GET','POST'])
def get_xxxx():
	if request.method == 'GET':
		return redirect('/index')
	ts = tools()
	name = request.form.get('name')
	html_txt = ts.getBdbk(name)
	
	res = str(html_txt).replace('href="/item','href="https://baike.baidu.com/item')\
								.replace('"/pic/',"https://baike.baidu.com/pic/")

	return json.dumps({'rwxx':res})


#返回对象详细信息
@us.route('/get_xxxxByUrl',methods =['GET','POST'])
def get_xxxxByUrl():
	if request.method == 'GET':
		return redirect('/index')
	ts = tools()
	url_select = 'https://baike.baidu.com'+request.form.get('url_select')
	html_txt = ts.getBdbkByUrl(url_select)
	res = str(html_txt).replace('href="/item','href="https://baike.baidu.com/item')\
								.replace('"/pic/',"https://baike.baidu.com/pic/")

	return json.dumps({'zlxx':res})



#返回百科词条列表
@us.route('/get_bklist',methods =['GET','POST'])
def get_bklist():
	if request.method == 'GET':
		return redirect('/index')
	ts = tools()
	#搜索页面传递uuid
	uuid = request.form.get('uuid')
	#资料贡献传递name
	name = request.form.get('name')
	html_txt =''
	html_list = ''
	if uuid:
		res = db.fetch_all('select need_name,detail from xxxxxx where uuid="{}"'.format(uuid,))[0]
		name = res.get('need_name')
		html_txt =res.get('detail')
	
	#不存在详细信息的情况下才去百科
	if not html_txt:
		html_list = ts.getBkList(name)
		html_txt = ts.getBdbk(name)
	res_txt = str(html_txt).replace('href="/item','href="https://baike.baidu.com/item')\
								.replace('"/pic/',"https://baike.baidu.com/pic/")
	res_list = html_list
								
	return json.dumps({'bklist':res_list,'bkxx':res_txt,'uuid':uuid})


#资料贡献
@us.route('/post_zlxx',methods =['GET','POST'])
def post_zlxx():
	if request.method == 'GET':
		return redirect('/index')

	formdata = request.form
	
	bz = formdata.get('bz')
	need_name = formdata.get('name')
	country = formdata.get('gj')
	intro = formdata.get('intro').replace('\'','')
	xxxx = formdata.get('xxxx').replace('\'','')
	rqq = formdata.get('rqq')
	rqz = formdata.get('rqz')
	fl = formdata.get('fl')
	
	try:
		if bz =='insert':
			uid = str(uuid.uuid1()).replace('-','')
			user_id = get_user().get('id')
			sql = '''insert into xxxxxx VALUES('{0}','{1}','{2}',
					'{3}','{4}','{5}',{6},{7},{8},sysdate(),'00',NULL,'')
				  '''.format(uid,need_name,country,intro,xxxx,fl,rqq,rqz,user_id)
			
			db.insert_one(sql)
			img_format , img_data = formdata.get('img').split(',')
			img_data = base64.b64decode(img_data)
			
			with open(os.getcwd()+'\\pro_flask\\static\\tmp_img\\'+uid+'.jpg','wb+') as f :
				f.write(img_data)

		elif bz =='update':
			uuid_update = formdata.get('uuid')
			sql = '''
					update xxxxxx 
					set need_name='{0}',country='{1}',intro='{2}',xxxx='{3}',fl='{4}',rqq={5},rqz={6},spjg='00'
					where uuid ='{7}' '''.format(need_name,country,intro,xxxx,fl,rqq,rqz,uuid_update)
			db.update(sql)
	except Exception as e:
		print(e)
		return json.dumps({'mes':'系统异常，请联系管理员！'})

	return json.dumps({'mes':'资料提交成功，等待审核！'})


#我的贡献

@us.route('/user_contr')
def user_contr():
	
	return render_template('user_zlgx.html')


#贡献榜单
@us.route('/gx_top')
def gx_top():
	sql ='''
			SELECT u.id,u.username,	count( 1 ) sl 
				FROM t_user_zlgx x,	t_users u 
			WHERE x.spjg = '01' AND x.user_id = u.id 
				GROUP BY u.username 
				ORDER BY count( 1 ) DESC  LIMIT 10
	'''
	count = db.fetch_all('select count(1)  count from xxxxxx where spjg = "01"')[0]
	res = db.fetch_all(sql)
	list_wait=[]
	if len(res)<10:
		list_wait = list(range(len(res)+1,11))
	return render_template('gx_top.html',ctx = {'res':res,'more':list_wait,'count':count})


#贡献榜单用户贡献明细
@us.route('/top_gxxx')
def top_gxxx():
	user_id = request.args.get('user_id')
	sql ='''
			SELECT	need_name,
        	CASE WHEN fl = '10' THEN '人物' 
		         WHEN fl = '20' THEN '建筑' ELSE '艺术' END lx,	country,
				      DATE_FORMAT( lrrq, '%Y-%m-%d' ) lrrq 
			FROM	xxxxxx 
			WHERE	spjg = '01' and user_id='{}'
	'''
	res = db.fetch_all(sql.format(user_id))
	return json.dumps(res)




#BOOTSTRAP TABLE
@us.route('/get_data')
def get_data():
	user_id = get_user().get('id')
	sql = '''SELECT
			uuid,	need_name,	country,	intro,	xxxx,	fl,	rqq,	rqz,
			DATE_FORMAT( lrrq, '%Y-%m-%d' ) lrrq,	
			case spjg when '00' then '未审批'
					when '01' then '审批通过'
					else '退回' end spjg,
			DATE_FORMAT(spsj, '%Y-%m-%d %H:%i:%s') spsj,	spyj 
			FROM	xxxxxx where user_id={}'''.format(user_id,)
	list_gxxx = db.fetch_all(sql)
	res = {}
	res['total'] = len(list_gxxx)
	res['rows'] = list_gxxx
	return json.dumps(res)


#删除贡献资料信息
@us.route('/post_err',methods =['GET','POST'])
def post_err():
	if request.method == 'GET':
		return redirect('/index')
 
	user = get_user()
	if not user:
		return json.dumps({'mes':'请登录后再提交！'})
	user_id = user.get('id')

	formdata = request.form
	uuid = formdata.get('uuid')
	errinfo = formdata.get('errinfo')
	sql = '''
			insert into xxxxxx values(UUID(),'{0}','{1}','{2}',null,sysdate())
		'''.format(user_id,uuid,errinfo)
	
	#插入记录
	db.update(sql)
	return json.dumps({'mes':'感谢您的纠错，我们会尽快核实！'})


#收藏
@us.route('/post_col',methods =['GET','POST'])
def post_col():
	if request.method == 'GET':
		return redirect('/index')
	user = get_user()
	if not user:
		return json.dumps({'mes':'请登录后再收藏！'})
	user_id = user.get('id')
	formdata = request.form
	uuid = formdata.get('uuid')
	res = db.fetch_all('select 1 from xxxxxx where user_id="{0}" and zluuid="{1}"'.format(user_id,uuid))
	if res:
		return json.dumps({'mes':'该信息已经收藏过!'})
	sql = '''
			insert into xxxxxx values(UUID(),'{0}','{1}',sysdate())
		'''.format(user_id,uuid)
	#插入记录
	db.update(sql)
	return json.dumps({'mes':'收藏成功！'})



#删除贡献资料信息
@us.route('/zlxx_delete',methods =['GET','POST'])
def zlxx_delete():
	if request.method == 'GET':
		return redirect('/index')

	formdata = request.form
	uuid = formdata.get('uuid')
	sql = '''delete from xxxxxx where uuid='{}' '''.format(uuid,)
	#删除记录
	db.update(sql)
	return json.dumps({'mes':'删除成功！'})



#用户信息修改
@us.route('/user_change',methods =['GET','POST'])
def user_change():
	if request.method == 'GET':
		return redirect('/index')

	formdata = request.form
	
	username = formdata.get('username')
	tel = formdata.get('tel')
	email = formdata.get('email')
	isIF = formdata.get('isIF')
	org_pwd = formdata.get('org_pwd')
	new_pwd = formdata.get('new_pwd')
	confirm_pwd = formdata.get('confirm_pwd')
	
	if isIF == 'true':
		res = db.fetch_all("select pwd from xxxxxx where username='{}'".format(username,))[0]
		pwd = tools.password_md5(org_pwd)
		if pwd != res.get('pwd'):
			return json.dumps({'mes':'原密码错误！'})
		db.update("update xxxxxx set tel='{0}',email='{1}',pwd='{2}' where username='{3}'".format(tel,email,tools.password_md5(confirm_pwd),username))
	db.update("update xxxxxx set tel='{0}',email='{1}' where username='{2}'".format(tel,email,username))
	return json.dumps({'mes':'修改成功！'})


